<template>
    <PopList :title="'热力图'" :showButton="true" @close="destroy" @ok="toggleHeatMap">
        <div class="bounds-inputs">
            <div class="bounds-group">
                <label>左上角:</label>
                <LabelInput v-model="bounds.topLeft[0]" :inputType="'number'" :label="'经度'" :step="0.000001"></LabelInput>
                <LabelInput v-model="bounds.topLeft[1]" :inputType="'number'" :label="'纬度'" :step="0.000001"></LabelInput>
            </div>
            <div class="bounds-group">
                <label>右下角:</label>
                <LabelInput v-model="bounds.bottomRight[0]" :inputType="'number'" :label="'经度'" :step="0.000001"></LabelInput>
                <LabelInput v-model="bounds.bottomRight[1]" :inputType="'number'" :label="'纬度'" :step="0.000001"></LabelInput>
            </div>
        </div>
        <LabelInput v-model="pointCount" :inputType="'number'" :label="'数据点数量'" :min="10" :max="1000"></LabelInput>
        <LabelInput v-model="radius" :inputType="'number'" :label="'热力点半径'" :min="10" :max="50"></LabelInput>
        <LabelInput v-model="maxValue" :inputType="'number'" :label="'最大值'" :min="1" :max="100"></LabelInput>
    </PopList>
</template>

<script setup lang="ts">
import { ref, reactive, inject, onBeforeUnmount } from "vue";
import PopList from "../../../components/PopList.vue";
import LabelInput from "../../../components/LabelInput.vue";
import { XbsjEarthUi } from "../../../scripts/xbsjEarthUi";
import Heatmap from "heatmap.js";
import { Message } from 'earthsdk-ui';
import * as Cesium from 'cesium';

interface Point {
  lat: number;
  lon: number;
  value: number;
}

interface HeatmapPoint {
  x: number;
  y: number;
  value: number;
}

const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi;

const bounds = reactive({
    topLeft: [118.296957, 32.314587],
    bottomRight: [118.318273, 32.297089]
});

const pointCount = ref(800);
const radius = ref(20);
const maxValue = ref(1600);

let heatmapInstance: any = null;
let polygonEntity: Cesium.Entity | null = null;
let heatmapElement: HTMLElement | null = null;

const toggleHeatMap = () => {
    if (polygonEntity) {
        destroy();
        Message.success('热力图已销毁');
    } else {
        createHeatMap();
    }
};

const createHeatMap = () => {
    const width = 1000;
    const height = 1000;

    const latMin = bounds.topLeft[1];
    const latMax = bounds.bottomRight[1];
    const lonMin = bounds.topLeft[0];
    const lonMax = bounds.bottomRight[0];

    const dataRaw: Point[] = Array.from({ length: pointCount.value }, () => ({
        lat: latMin + Math.random() * (latMax - latMin),
        lon: lonMin + Math.random() * (lonMax - lonMin),
        value: Math.floor(Math.random() * maxValue.value),
    }));

    const points: HeatmapPoint[] = dataRaw.map(dataItem => ({
        x: Math.floor(((dataItem.lat - latMin) / (latMax - latMin)) * width),
        y: Math.floor(((dataItem.lon - lonMin) / (lonMax - lonMin)) * height),
        value: Math.floor(dataItem.value),
    }));

    heatmapElement = document.getElementById("heatmap");
    if (!heatmapElement) {
        heatmapElement = document.createElement("div");
        heatmapElement.id = "heatmap";
        heatmapElement.setAttribute(
            "style",
            "width:1000px;height:1000px;margin: 0px;display: none;"
        );
        document.body.appendChild(heatmapElement);
    }

    heatmapInstance = Heatmap.create({
        container: heatmapElement,
        radius: radius.value
    });

    heatmapInstance.setData({
        max: maxValue.value,
        data: points,
    });

    const viewer = xbsjEarthUi.activeViewer?.innerViewer?.viewer;
    if (!viewer) {
        Message.error('viewer 未初始化');
        return;
    }

    polygonEntity = viewer.entities.add({
        polygon: {
            hierarchy: new Cesium.PolygonHierarchy([
                Cesium.Cartesian3.fromDegrees(118.296957, 32.307046),
                Cesium.Cartesian3.fromDegrees(118.297008, 32.303089),
                Cesium.Cartesian3.fromDegrees(118.29956, 32.297089),
                Cesium.Cartesian3.fromDegrees(118.304248, 32.29982),
                Cesium.Cartesian3.fromDegrees(118.30971, 32.302973),
                Cesium.Cartesian3.fromDegrees(118.318273, 32.307989),
                Cesium.Cartesian3.fromDegrees(118.315322, 32.314587),
                Cesium.Cartesian3.fromDegrees(118.305255, 32.3093),
            ]),
            material: heatmapInstance.getDataURL(),
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        }
    });

    Message.success('热力图创建成功');
};

const destroy = () => {
    const viewer = xbsjEarthUi.activeViewer?.innerViewer?.viewer;
    if (viewer && polygonEntity) {
        viewer.entities.remove(polygonEntity);
        polygonEntity = null;
    }

    if (heatmapInstance) {
        heatmapInstance.__store.destroy();
        heatmapInstance = null;
    }

    if (heatmapElement) {
        heatmapElement.remove();
        heatmapElement = null;
    }
};

onBeforeUnmount(() => {
    destroy();
});
</script>

<style scoped>
/* 原有样式保持不变 */
.bounds-inputs {
    margin: 10px 0;
}

.bounds-group {
    margin: 5px 0;
}

.bounds-group label {
    color: #e6e6e6;
    font-size: 12px;
    margin-bottom: 5px;
    display: block;
}
</style>